package com.dream.oauth2.controller;

import com.dream.oauth2.model.entity.OAuth2UserInfo;
import com.dream.oauth2.model.entity.User;
import com.dream.oauth2.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/current")
    public OAuth2UserInfo getCurrentUser(HttpSession session) {
        OAuth2UserInfo user = (OAuth2UserInfo) session.getAttribute("user");
        if (user == null) {
            throw new RuntimeException("用户未登录");
        }
        return user;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> registerRequest) {
        try {
            String username = registerRequest.get("username");
            String password = registerRequest.get("password");
            String nickname = registerRequest.get("nickname");
            String email = registerRequest.get("email");

            // 参数验证
            if (username == null || username.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("密码不能为空");
            }
            if (nickname == null || nickname.trim().isEmpty()) {
                nickname = username; // 如果昵称为空，使用用户名作为昵称
            }

            User user = userService.register(username, password, nickname, email);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "注册成功");
            response.put("username", user.getUsername());
            
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
} 